package br.senai.modelo.impl;

import javax.persistence.EntityManager;

import br.senai.modelo.BaseDAO;

public class BaseDAOImpl implements BaseDAO {
	
	protected EntityManager entityManager;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public void salvar(Object entidade) {
		openTransaction();
		try {
			this.entityManager.merge(entidade);
			commitTransaction();
		} catch (Exception e) {
			e.printStackTrace();
			rollbackTransaction();
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void remover(Class classe, Integer id) {
		openTransaction();
		try {
			Object entidade = entityManager.find(classe, id);
			this.entityManager.remove(entidade);
			commitTransaction();
		} catch (Exception e) {
			e.printStackTrace();
			rollbackTransaction();
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object buscarPorId(Class classe, Integer id) {
		return entityManager.find(classe, id);
	}
	
	protected void openTransaction() {
		this.entityManager.getTransaction().begin();
	}
	
	protected void commitTransaction() {
		this.entityManager.getTransaction().commit();
	}
	
	protected void rollbackTransaction() {
		this.entityManager.getTransaction().rollback();
	}

}
